<template>
  <div ref="chartRef" :id="chartId" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import {onMounted, onUnmounted, defineProps, watch, ref} from 'vue';

// 定义接收的 props
const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  },
  chartId: {
    type: String,
    required: true
  }
});

const chartRef = ref(null);
let myChart;

// 计算 labelLine 长度的函数
const calculateLabelLineLength = () => {
  const chartDom = chartRef.value;
  const width = chartDom.offsetWidth;
  // 根据图表宽度动态计算长度
  const length = Math.max(10, width * 0.05);
  const length2 = Math.max(20, width * 0.1);
  return { length, length2 };
};

// 计算图例字体大小的函数
const calculateLegendFontSize = () => {
  const windowWidth = window.innerWidth;
  return `clamp(10px, 1vw, 16px)`; // 根据视口宽度动态调整字体大小
};

const updateChart = () => {
  // 提取图例数据
  const legendData = props.chartData.map(item => item.name);

  const { length, length2 } = calculateLabelLineLength();
  const legendFontSize = calculateLegendFontSize();

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical', // 修改为垂直反向排列
      left: 'left',
      data: legendData, // 设置图例数据
      textStyle: {
        color: '#e2ebee',
        fontWeight: 'bold',
        fontSize: legendFontSize
      },
      // 自定义图例内容，展示名称和数量
      formatter: function (name) {
        const item = props.chartData.find(item => item.name === name);
        return `${name}: ${item ? item.value : 0}`;
      }
    },
    series: [
      {
        name: '人数',
        type: 'pie',
        radius: ['70%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
          formatter: '{c}',
          textStyle: {
            color: '#5d90ee',
          }
        },
        labelLine: {
          show: true,
          length,
          length2
        },
        data: props.chartData
      }
    ]
  };

  if (option && typeof option === 'object') {
    myChart.setOption(option);
  }
};

onMounted(() => {
  const chartDom = chartRef.value;
  if (myChart) {
    myChart.dispose(); // 销毁旧实例
  }
  myChart = echarts.init(chartDom);
  updateChart();

  // 定义处理窗口大小变化的函数
  const handleResize = () => {
    if (myChart) {
      const {length, length2} = calculateLabelLineLength();
      const legendFontSize = calculateLegendFontSize();
      myChart.setOption({
        legend: {
          textStyle: {
            fontSize: legendFontSize
          }
        },
        series: [
          {
            labelLine: {
              length,
              length2
            }
          }
        ]
      });
      myChart.resize();
    }
  };

  // 监听窗口的 resize 事件
  window.addEventListener('resize', handleResize);

  // 在组件卸载时移除事件监听和销毁实例
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    if (myChart) {
      myChart.dispose();
      myChart = null;
    }
  });
});

// 监听 chartData 的变化，更新图表
watch(() => props.chartData, () => {
  const chartDom = chartRef.value;
  if (myChart) {
    myChart.dispose(); // 销毁旧实例
  }
  myChart = echarts.init(chartDom);
  updateChart();
});
</script>